package com.sparrow.manage.auth.shiro;

import com.sparrow.manage.user.User;
import com.sparrow.manage.user.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

/**
 * shiro账户认证服务
 * SQLite
 */
public class ShiroRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

    private static final ShiroRealm INSTANCE = new ShiroRealm();

    private UserService userService;

    public void setUserService(UserService userService) {
        if(userService != null){
            this.userService = userService;
        }
    }

    private ShiroRealm(){}

    public static ShiroRealm instance(){
        return INSTANCE;
    }


    /*
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /*
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String loginname = token.getUsername();

        logger.info(loginname + "login.");

        User user = userService.queryByLoginname(loginname);

        if(user == null){
            throw new UnknownAccountException();
        }

        String encodePassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());

        ShiroUser shiroUser = new ShiroUser();
        shiroUser.setLoginname(loginname);
        shiroUser.setName(user.getName());

        return new SimpleAuthenticationInfo(shiroUser, encodePassword, getName());
    }

}
